package com.hankol.community

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.load
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.share.SharePopupWindow
import com.google.android.material.appbar.AppBarLayout
import com.baselibrary.utils.EmptyViewUtil
import com.hankol.community.adapter.ColumnDetailsListAdapter
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.ColumnDetailBean
import com.hankol.community.bean.ColumnDetailsListBean
import com.hankol.community.bean.ShowShare2Bean
import com.hankol.community.databinding.ActivityColumnDetailsBinding
import com.hankol.community.viewmodel.CommunityViewModel
import java.util.*


/**
 * @description 专栏详情
 *@author wxp
 */
@Route(path = ActivityRouter.COMMUNITY.COLUMN_DETAIL)
class ColumnDetailsActivity : BaseActivity(), View.OnClickListener {

    private lateinit var binding: ActivityColumnDetailsBinding
    private lateinit var mViewModel: CommunityViewModel

    private val adapter by lazy { ColumnDetailsListAdapter() }
    private val mLayoutManager by lazy { LinearLayoutManager(this) }
    var page = 1
    private var hasnext: Boolean = false
    var id = 0
    private var mShowSharePop: SharePopupWindow? = null
    private var dateBean: ColumnDetailBean? = null
    val communityHelp: CommunityHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)

    //曝光数
    var exposureCnt = 0

    override fun getLayoutId(): Int {
        return R.layout.activity_column_details
    }

    override fun init() {
        //获取页面开始时间
        SensorsDataManager.instance.onCreateTime()
        SensorsDataManager.instance.setFormPagePos("专栏")
        binding = getDataBinding<ActivityColumnDetailsBinding>()
        mViewModel = getActivityViewModelProvider(this).get(CommunityViewModel::class.java)

        if (intent.extras.checkNotNull()) {
            if (ARouterUtils.parseParams(intent.extras!!, "id").size > 0) {
                id = ARouterUtils.parseParams(intent.extras!!, "id")[0].toInt()
            }
        }
        initView()
        reqColumnDetailData()
        loadData()
        initListener()
        initObserver()
    }

    private fun initObserver() {
        //专栏信息
        mViewModel.columnDetailLD.observe(this, Observer {
            setDataInfo(it)
        })

        mViewModel.columnDetailMld.observe(this, Observer {
            hideLoadingDialog()
            binding.smartRefresh.finishRefresh()
            if (it == null || it.data?.size == 0) {
                //无数据
                if (page != 1) {
                    binding.smartRefresh.finishLoadMore()
                }
                adapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_COLUMN_DETAIL, binding.rvForumClassify)
            } else {
                if (it.data != null) {
                    hasnext = it.totalPage != adapter.data.size
                    binding.smartRefresh.finishLoadMore()
                    if (page == 1) {
                        adapter.setNewData(it.data)
                    } else {
                        adapter.addData(it.data!!)
                    }
                    page++
                }
            }
        })
        //请求好友列表
//        mViewModel.friendLiveData.observe(this, Observer {
//            mShowSharePop?.setShareFriendAdapter(mViewModel.changeFriend(it))
//        })
        //收藏&取消收藏
        mViewModel.collectionLiveData.observe(this, Observer { it ->
            if (it) {
                dateBean?.let {
                    it.favorited = if (binding.imgCollectTop.isSelected) 0 else 1
                    collectState(dateBean?.favorited == 1)
                }
                //刷新
                reqColumnDetailData()
            }
        })
    }

    private fun setDataInfo(bean: ColumnDetailBean?) {
        this.dateBean = bean
        bean?.let {
            binding.tvColumnName.text = bean.name.checkValue()
            binding.tvTopTitle.text = bean.name.checkValue()
            //简介
            SpanUtils.setIcon(this, binding.tvDesc, it.desc)
            //封面
            binding.imgCover.load(this, bean.infoCover.checkValue())
            binding.tvPeriodsPlayNum.text = "${NumberUtils.formatBigNum("${bean.favoriteNum}")} 收藏 · ${bean.articleNum} 内容"
            collectState(bean.favorited == 1)
            //收藏头像
            binding.avatarsViewPulpitHome.setData(this, bean.favoriteUserIconList, false)
            binding.avatarsViewPulpitHome.visibility = if (bean.favoriteUserIconList.size == 0) View.GONE else View.VISIBLE
            binding.tvPeriodsPlayNum.visibility = if (bean.favoriteUserIconList.size == 0) View.GONE else View.VISIBLE
            SensorsDataManager.instance.articleClick("${id}",it.name.checkValue())
        }
    }

    private fun collectState(favorite: Boolean) {
        binding.imgCollectTop.isSelected = favorite
        binding.imgContentCollect.isSelected = favorite
        binding.imgCollectTop.setImageResource(if (favorite) R.drawable.ic_pul_false_collection else R.drawable.ic_pul_true_collection)
        binding.imgContentCollect.setImageResource(if (favorite) R.drawable.ic_pul_false_collection else R.drawable.ic_pul_true_collection)
    }

    private fun initListener() {
        binding.backImageView.setOnClickListener { finish() }
        binding.imgTopShare.setOnClickListener(this)
        binding.imgCollectTop.setOnClickListener(this)
        binding.imgContentCollect.setOnClickListener(this)
        binding.tvDesc.setOnClickListener(this)
        adapter.setOnItemClickListener { adapter, view, position ->
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val bean = adapter.data[position] as ColumnDetailsListBean
                bean.readNum = bean.readNum.plus(1)
                adapter.notifyItemChanged(position)
                //进入对应详情页面
                val map = HashMap<String, Any>()
                map["aid"] = bean.id
                ARouterUtils.jump(ActivityRouter.COMMUNITY.ARTICLE_DETAIL, map)
            }
        }
        binding.smartRefresh.setOnRefreshListener {
            page = 1
            loadData()
            reqColumnDetailData()
        }
        binding.smartRefresh.setOnLoadMoreListener {
            if (hasnext) {
                loadData()
            } else {
                binding.smartRefresh.finishLoadMore()
            }
        }
        binding.ablTop.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val offset = ScreenUtils.dpToPx(158) + binding.tvPeriodsPlayNum.height
            if (-verticalOffset in 0..offset) {
                binding.tvTopTitle.visibility = View.GONE
                binding.imgCollectTop.visibility = View.GONE
            } else {
                binding.tvTopTitle.visibility = View.VISIBLE
                binding.imgCollectTop.visibility = View.VISIBLE
            }
        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tv_desc -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    SensorsDataManager.instance.specialColumnDescClick(dateBean?.name.checkValue())
                    //专栏简介
                    val hashMap = HashMap<String, Any>()
                    hashMap["title"] = dateBean?.name.checkValue()
                    hashMap["content"] = dateBean?.desc.checkValue()
                    ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_CONTENT_DETAIL, hashMap)
                }
            }
            R.id.img_top_share -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    //分享弹窗
                    dateBean?.let {
                        mShowSharePop = mViewModel.showShare(columnDetail2showShare(it), this, communityHelp,false,false)
                    }
                }
            }
            R.id.img_collect_top, R.id.img_content_collect -> {
                //收藏
                dateBean?.let {
                    mViewModel.reqCollection(!binding.imgCollectTop.isSelected, 6, it.id)
                }
            }
        }
    }

    private fun columnDetail2showShare(bean: ColumnDetailBean): ShowShare2Bean {
        return ShowShare2Bean().apply {
            id = bean.id
            showType = 1
            cover = bean.infoCover
            title = bean.name.checkValue()
            content = bean.desc.checkValue()
            url = Constants.COLUMN_SHARE_URL + id
        }
    }

    private fun reqColumnDetailData() {
        mViewModel.reqColumnDetailData(id)
    }

    private fun initView() {
        BannerSizeUtil.setBannerSizeValue(binding.imgCover, 347, 129)
        binding.rvForumClassify.setAdapter(adapter)
        binding.rvForumClassify.layoutManager = mLayoutManager
        //曝光监听
        binding.rvForumClassify.addOnScrollListener(object : RecyclerViewExposureListener() {
            override fun exposureView(view: View?, index: Int) {
                exposureCnt = index.plus(2)
            }
        })
    }

    fun loadData() {
        showLoadingDialog()
        mViewModel.reqColumnDetailList(page, id)
    }

    override fun onDestroy() {
        dateBean?.let {
            if (it.favorited == 0) EventBusUtils.sendNotify(MessageBus.msgId_column_collection_false)
        }
        super.onDestroy()
        //获取页面结束时间
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L) {
            SensorsDataManager.instance.browseSpecialColumn(dateBean?.name.checkValue(), exposureCnt.div(adapter.data.size.toFloat()).times(100).toInt())
        }
    }
}